// API服务基础配置
const API_BASE_URL = '/api';

// 通用请求方法
async function request(url, method = 'GET', data = null, token = null) {
  const headers = {
    'Content-Type': 'application/json'
  };
  
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  
  const options = {
    method,
    headers
  };
  
  if (data && (method === 'POST' || method === 'PUT')) {
    options.body = JSON.stringify(data);
  }
  
  try {
    const response = await fetch(`${API_BASE_URL}${url}`, options);
    const result = await response.json();
    return result;
  } catch (error) {
    console.error('API请求错误:', error);
    return {
      code: 500,
      message: '网络请求失败，请稍后重试',
      data: null
    };
  }
}

// 用户认证相关API
const authAPI = {
  // 用户注册
  register: (phone, password, verifyCode, nickname) => {
    return request('/auth/register', 'POST', {
      phone,
      password,
      verify_code: verifyCode,
      nickname
    });
  },
  
  // 用户登录
  login: (phone, password) => {
    return request('/auth/login', 'POST', {
      phone,
      password
    });
  },
  
  // 获取用户信息
  getUserInfo: (token) => {
    return request('/auth/user-info', 'GET', null, token);
  },
  
  // 更新用户信息
  updateUserInfo: (token, userInfo) => {
    return request('/auth/user-info', 'PUT', userInfo, token);
  },
  
  // 修改密码
  changePassword: (token, oldPassword, newPassword) => {
    return request('/auth/change-password', 'PUT', {
      oldPassword,
      newPassword
    }, token);
  }
};

// 八字命理相关API
const baziAPI = {
  // 生成八字
  generateBazi: (token, birthYear, birthMonth, birthDay, birthHour) => {
    return request('/bazi/generate', 'POST', {
      birth_year: birthYear,
      birth_month: birthMonth,
      birth_day: birthDay,
      birth_hour: birthHour
    }, token);
  },
  
  // 获取八字分析
  getBaziAnalysis: (token, baziId) => {
    return request(`/bazi/analysis/${baziId}`, 'GET', null, token);
  },
  
  // 获取八字详细分析（付费内容）
  getBaziDetail: (token, baziId) => {
    return request(`/bazi/detail/${baziId}`, 'GET', null, token);
  }
};

// 性格分析相关API
const characterAPI = {
  // 获取性格分析
  getCharacterAnalysis: (token, baziId) => {
    return request(`/character/analysis/${baziId}`, 'GET', null, token);
  },
  
  // 获取今日运势
  getDailyFortune: (token) => {
    return request('/character/daily-fortune', 'GET', null, token);
  },
  
  // 获取性格详细分析（付费内容）
  getCharacterDetail: (token, baziId) => {
    return request(`/character/detail/${baziId}`, 'GET', null, token);
  }
};

// 风水住宅相关API
const fengshuiAPI = {
  // 提交风水分析请求
  submitFengshuiAnalysis: (token, data) => {
    return request('/fengshui/submit', 'POST', data, token);
  },
  
  // 获取风水分析结果
  getFengshuiAnalysis: (token, fengshuiId) => {
    return request(`/fengshui/analysis/${fengshuiId}`, 'GET', null, token);
  },
  
  // 获取风水详细分析（付费内容）
  getFengshuiDetail: (token, fengshuiId) => {
    return request(`/fengshui/detail/${fengshuiId}`, 'GET', null, token);
  }
};

// 小工具相关API
const toolAPI = {
  // 获取万年历数据
  getCalendar: (year, month) => {
    return request(`/tool/calendar?year=${year}&month=${month}`, 'GET');
  },
  
  // 获取星座信息
  getZodiacSign: (month, day) => {
    return request(`/tool/zodiac-sign?month=${month}&day=${day}`, 'GET');
  },
  
  // 获取生肖信息
  getChineseZodiac: (year) => {
    return request(`/tool/chinese-zodiac?year=${year}`, 'GET');
  },
  
  // 姓名测算
  nameAnalysis: (name) => {
    return request('/tool/name-analysis', 'POST', { name });
  },
  
  // 周公解梦
  dreamInterpretation: (keyword) => {
    return request('/tool/dream', 'POST', { keyword });
  }
};

// 支付相关API
const paymentAPI = {
  // 创建订单
  createOrder: (token, productType, productId, amount) => {
    return request('/payment/create-order', 'POST', {
      product_type: productType,
      product_id: productId,
      amount
    }, token);
  },
  
  // 支付订单
  payOrder: (token, orderNo, paymentType) => {
    return request('/payment/pay', 'POST', {
      order_no: orderNo,
      payment_type: paymentType
    }, token);
  },
  
  // 查询订单状态
  getOrderStatus: (token, orderNo) => {
    return request(`/payment/order-status/${orderNo}`, 'GET', null, token);
  },
  
  // 获取订单列表
  getOrderList: (token) => {
    return request('/payment/order-list', 'GET', null, token);
  },
  
  // 开通VIP会员
  activateVip: (token) => {
    return request('/payment/activate-vip', 'POST', {}, token);
  }
};
